<!DOCTYPE html>
<html>
<head>
<title>Websocket Demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<style>
.border {
	border: 1px solid black;
}

.table_letter {
	display: inline-block;
	width: 20px;
	text-align: center;
}

#messages {
	border: dotted 1px #444444;
	font: 12px arial, sans-serif;
}

#messages>p {
	padding: 0px;
	margin: 0px;
}
</style>
<script>
	var messages;
	var form;
	var inputBox;
	function build_grid() {
		var the_grid = $('#the_grid');

		var table = '<div>'
		for ( var i = 0; i < 25; i++) {
			table += '<div>'
			for ( var e = 0; e < 51; e++) {
				table += '<span id="x_' + i +'_y_'+ e +'" class="border table_letter">&nbsp;</span>';
			}
			table += '<div>'
		}
		table += '<div>'

		the_grid.html(table);
	}

	var string = '';
	function grid_func(json) {

		set_grid(json);
		
		/*if (json == 'clear') {
			set_grid(string);
			string = '';
		} else {
			string += json
		}*/
	}
	function set_grid(json) {

		var obj;

		try {
			obj = jQuery.parseJSON(json);
		} catch (e) {
			// alert(e + json); //error in the above string(in this case,yes)!
		}

		// finish
		var letters = $('.table_letter');

		// clear them all first
		letters.css('background-color', 'white');

		$.each(obj, function(i, item) {

			var x = item[0];
			var y = item[1];

			set_colors(x, y);
		});
	}
	function set_colors(x, y) {

		$('#x_' + y + '_y_' + x).css('background-color', 'green');

	}
	function log_msg(msg) {
		var p = document.createElement("p");
		p.innerHTML = msg;
		messages.appendChild(p);
	}
	function doInit() {
		inputBox = document.getElementById("message");
		messages = document.getElementById("messages");
		form = document.getElementById("form");
		var s;
		try {
			var host = "ws://localhost:4545/";
			if (window.location.hostname) {
				host = "ws://" + window.location.hostname + ":4545/";
			}
			s = new WebSocket(host);
			s.onopen = function(e) {
				log_msg("connected...");
			};
			s.onclose = function(e) {
				log_msg("connection closed.");
				doInit();
			};
			s.onerror = function(e) {
				log_msg("connection error.");
			};
			s.onmessage = function(e) {
				log_msg("message: " + e.data);

				grid_func(e.data);
			};
		} catch (ex) {
			log_msg("connection exception:" + ex);
		}
		form.addEventListener("submit", function(e) {
			e.preventDefault();
			s.send(inputBox.value);
			inputBox.value = "";
		}, false);
	}
	function go() {
		build_grid();
		doInit();
	}
</script>
</head>
<body onload="go()">
	<div id="the_grid"></div>
	<br />
	<form id="form">
		<input type="text" id="message">
		<button type="submit">Send</button>
	</form>
	<br />
	<div id="messages"></div>
</body>
</html>